<?php
namespace app\admin\controller;

use think\facade\Db;
use think\facade\View;
class Suppliers extends Base
{
    /**
    CREATE TABLE `sy_suppliers` (
    `id` smallint(5) unsigned NOT NULL AUTO_INCREMENT COMMENT '供应商ID',
    `cid` int(11) NOT NULL DEFAULT '0' COMMENT '分类id',
    `username` varchar(255) NOT NULL DEFAULT '' COMMENT '登录账号',
    `password` varchar(255) NOT NULL DEFAULT '' COMMENT '登录密码',
    `name` varchar(255) NOT NULL DEFAULT '' COMMENT '供应商名称',
    `desc` mediumtext NOT NULL COMMENT '供应商描述',
    `is_check` tinyint(1) unsigned NOT NULL DEFAULT '1' COMMENT '供应商状态',
    `nickname` varchar(255) NOT NULL DEFAULT '' COMMENT '供应商联系人',
    `mobile` varchar(20) NOT NULL DEFAULT '' COMMENT '供应商电话',
    `province` int(10) unsigned DEFAULT NULL COMMENT '所在省份id',
    `city` int(10) unsigned DEFAULT NULL COMMENT '所在城市id',
    `user_id` int(11) DEFAULT '0',
    `district` int(11) DEFAULT '0',
    `w_time` int(10) DEFAULT '0',
    `logo` varchar(255) DEFAULT NULL,
    `pics` varchar(255) DEFAULT NULL,
    `last_login` int(11) NOT NULL DEFAULT '0' COMMENT '最后一次登录时间',
    `last_ip` varchar(255) NOT NULL DEFAULT '' COMMENT '最后一次登录ip',
    `content` text,
    `longitude` varchar(255) DEFAULT NULL,
    `latitude` varchar(255) DEFAULT NULL,
    `zhengming` varchar(255) DEFAULT NULL,
    `address` varchar(255) DEFAULT NULL,
    PRIMARY KEY (`id`) USING BTREE
    ) ENGINE=MyISAM AUTO_INCREMENT=6 DEFAULT CHARSET=utf8 ROW_FORMAT=DYNAMIC;

     */
    public function index(){
        if(IS_AJAX){
            $page = input('page');
            $limit = input('limit')?:15;
            $map = [];
            if(input('id')){
                $map['o.id'] = input('id');
            }
            if(input('name')){
                $map['o.name'] = ['like','%'.input('name').'%'];
            }

            $count = Db::name('suppliers')->alias('a')->where($map)->count();

            $field = 'a.*';
            $list = Db::name('suppliers')
                ->alias('a')
                ->field($field)
                ->where($map)
                ->order('a.id desc ')
                ->page($page,$limit)
                ->select();
            foreach($list as $k=>$v){
                $v['w_time'] = date('Y-m-d H:i:s',$v['w_time']);
                $list[$k] = $v;
            }
            return json(['code'=>0,'msg'=>'查询成功','count'=>$count,'data'=>$list]);
        }
        return View::fetch();
    }
    public function edit(){
        $id = input('id');
        $info = Db::name('suppliers')->where('id',$id)->find();
        if(request()->isPost()){
            Db::startTrans();
            $params = input();
            $data = [];
            $data['username'] = $params['username'];
            if(!empty($params['password'])){
                $data['password'] = encrypt($params['password']);
            }
            $data['user_id'] = $params['user_id']??'';
            $data['name'] = $params['name']??'';
            $data['logo'] = $params['logo']??'';
            $data['desc'] = $params['desc']??'';
            $data['nickname'] = $params['nickname']??'';
            $data['mobile'] = $params['mobile']??'';
            $data['pics'] = $params['pics']??'';
            $data['zhengming'] = $params['zhengming']??'';
            $data['content'] = $params['content']??'';
            $data['status'] = $params['status']??'';
            $data['province'] = $params['province'];
            $data['city'] = $params['city'];
            $data['district'] = $params['district'];
            $data['address'] = $params['address'];
            $data['longitude'] = $params['longitude']??"";
            $data['latitude'] = $params['latitude']??"";
            $data['w_time'] = time();
            $data['content'] = $params['content'];

            $data['weixin'] = $params['weixin']??"";
            $data['aliaccount'] = $params['aliaccount']??'';
            $data['bankname'] = $params['bankname']??'';
            $data['bankcarduser'] = $params['bankcarduser']??'';
            $data['bankcardnum'] = $params['bankcardnum']??'';
            $data['bankbranch'] = $params['bankbranch']??'';
            $data['status'] = $params['status'];
            if(!empty($params['id'])){
                Db::name('suppliers')->where('id',$params['id'])->update($data);
                //echo Db::getLastSql();exit;
                $admin_id = Db::name('admin')->where('suppliers_id',$params['id'])->value('admin_id');
                if($admin_id){
                    $data_a = [];
                    $data_a['user_name'] = $params['username'];
                    if(!empty($data['password'])){
                        $data_a['password'] = $data['password'];
                    }
                    Db::name('admin')->where('admin_id',$admin_id)->update($data_a);
                }else{
                    $supply_id = $params['id'];
                    $role_id = Db::name('admin_role')->where('is_supply',1)->value('role_id');
                    //插入一个admin数据
                    Db::name('admin')->insert([
                        'user_name' => $params['username'],
                        'password' => encrypt($params['password']),
                        'add_time' => time(),
                        'role_id' => $role_id,
                        'suppliers_id' => $supply_id
                    ]);
                }


            }else{
                $supply_id = Db::name('suppliers')->insertGetId($data);
                $role_id = Db::name('admin_role')->where('is_supply',1)->value('role_id');
                //插入一个admin数据
                Db::name('admin')->insert([
                    'user_name' => $params['username'],
                    'password' => encrypt($params['password']),
                    'add_time' => time(),
                    'role_id' => $role_id,
                    'suppliers_id' => $supply_id
                ]);
            }
            Db::commit();
            return json(['status'=>1,'msg'=>'操作成功！']);
        }else{
            View::assign('info',$info);
            $is_supply = 0;
            if(SID){
                $is_supply=1;
            }
            View::assign('is_supply',$is_supply);
            $qq_map_key = tpCache('basic.qq_map_key');
            View::assign('qq_map_key',$qq_map_key);
            return View::fetch();
        }
    }

    public function delete(){
        $ids = input('post.ids/a');
        Db::name('suppliers')->where(['id'=>['in',$ids]])->delete();
        return json(['status'=>1,'msg'=>'删除成功']);
    }
    public function choosesupply(){
        if(IS_POST){
            $id = input('post.id/d');
            $info = Db::name('suppliers')->where('id',$id)->find();
            return json(['status'=>1,'data'=>$info]);
        }else{
            return View::fetch();
        }
    }

    //商家货款提现
    public function withdraw(){
        $sid = $this->sid;
        $supply = Db::name('suppliers')->where('id',$sid)->find();
        if(request()->isPost()){
            $money_type = 's_money';
            $config = tpCache('wallet.tx_'.$money_type);
            if($config['status']==0){
//                return json(['status'=>0,'msg'=>'提现功能未开启']);
            }
            if(!empty($config['withdraw_date'])){
                $withdraw_date = explode(',',$config['withdraw_date']);
                $day = date('d');
                if($withdraw_date && !in_array($day,$withdraw_date) && !in_array(intval($day),$withdraw_date)){
//                    return json(['status'=>0,'msg'=>'每月'.$config['withdraw_date'].'可以提现']);
                }
            }
            //判断是否有正在进行中的
            $have = Db::name("withdraw_log")->where(['user_id'=>$this->sid,'status'=>0,'tx_type'=>'s_money'])->find();
            if($have){
                $result = [
                    'status' => false,
                    'msg' => '您已经有提现记录，正在审核中',
                ];
                return json($result);
            }

            $post = input();
            $money=floatval($post['money']);

            if(!$money || $money<=0) {
                $result = [
                    'status' => false,
                    'msg' => '请输入正确的兑换金额',
                ];
                return json($result);
            }

            //到账方式
            $dz_type = $post['dz_type'];;//$post['dz_type'];
            $address = '';
            switch($dz_type){
                case "wechat":
                    if($supply['weixin']==''){
                        return json(['status'=>0,'msg'=>'请先绑定微信']);
                    }
                    break;
                case "alipay":
                    if($supply['zhifubao']=='' || $supply['bank_huming']==''){
                        return json(['status'=>0,'msg'=>'请先绑定支付宝']);
                    }
                    break;
                case "bank":
                    if($supply['bankname']=='' || $supply['bankcarduser']=='' || $supply['bankcardnum']==''){
                        return json(['status'=>0,'msg'=>'请先完善银行卡信息']);
                    }
                    break;
                default:
                    return json(['status'=>0,'msg'=>'请选择到账方式']);
            }

            if($money>$config['max'] && $config['max']>0) {
                $result = [
                    'status' => false,
                    'msg' => '每次兑换金额不能大于'.$config['max'],
                    'url' => ''
                ];
                return json($result);
            }
            if($money<$config['min']) {
                $result = [
                    'status' => false,
                    'msg' => '兑换额度不能小于'.$config['min'],
                    'url' => ''
                ];
                return json($result);
            }

            $fee=0;$total=$price=$money;
            if($config['fee']){
                $fee=$money*$config['fee']/100;
                //额外扣
                if($config['fee_type']==1){
                    $total+=$fee;
                }else{
                    $price-=$fee;
                }
            }
            $changebl = $config['changebl']>0?$config['changebl']:1;
            $realprice = bcmul($price,$changebl,2);

            if($supply['s_money']<$total) {
                $result = [
                    'status' => false,
                    'msg' => '余额不足，不能兑换',
                    'url' => ''
                ];
                return json($result);
            }

            Db::startTrans();
            $result=qianbao_supply($this->sid,-$total,$money_type,'兑换','商家货款提现');
            if($result['status']) {
                $data=array();
                $data['username'] = $supply['username'];
                $data['user_id'] =  $supply['id'];;
                $data['money'] = $money;
                $data['fee'] = $fee;
                $data['price'] = $realprice;
                $data['status'] = 0;
                $data['addtime'] = time();
                $data['tx_type' ]= $money_type;
                $data['bank_name'] = $supply['bankname'];
                $data['bank_card'] = $supply['bankcardnum'];
                $data['realname'] = $supply['bankcarduser'];
                $data['bank_branch'] = $supply['bankbranch'];
                $data['weixin'] = $supply['weixin'];
                $data['zhifubao'] = $supply['aliaccount'];
                $data['uadd'] = $address;
                $data['dz_type'] = $dz_type;
                $data['total'] = $total;
                $rss=Db::name("withdraw_log")->add($data);
                if($rss) {
                    Db::commit();
                    $result = [
                        'status' => true,
                        'msg' => '兑换申请成功，请等待平台审核！',
                        'url' => ''
                    ];
                    return json($result);
                }else{
                    Db::rollback();
                    $result = [
                        'status' => false,
                        'msg' => '兑换失败，更新兑换记录失败',
                        'url' => ''
                    ];
                    return json($result);
                }
            }else{
                Db::rollback();
                $result = [
                    'status' => false,
                    'msg' => '兑换失败'.$result['msg'],
                    'url' => ''
                ];
                return json($result);
            }
        }else{
            View::assign('supply',$supply);
            return View::fetch();
        }
    }
}